//https://leetcode.cn/problems/course-schedule/

class Solution {
public:
    bool canFinish(int numCourses, vector<vector<int>>& prerequisites) {
        //准备工作
        //创建邻接表
        unordered_map<int, vector<int>> edges(numCourses);
        //存储每一个顶点的入度
        vector<int> in(numCourses);

        //建图
        for (auto& e : prerequisites)
        {
            int a = e[0], b = e[1];  //b->a
            edges[b].push_back(a);
            in[a]++;
        }

        //拓扑排序
        queue<int> q;
        //所有入度为0的顶点入队列
        for (int i = 0; i < in.size(); i++)
        {
            if (in[i] == 0)
                q.push(i);
        }

        //出队列
        while (q.size())
        {
            int t = q.front();
            q.pop();

            for (auto e : edges[t])
            {
                in[e]--;
                if (in[e] == 0)
                {
                    q.push(e);
                }
            }

        }

        //判断是否带环
        for (auto e : in)
        {
            if (e) return false;
        }

        return true;

    }
};